/**
 * create by young (young2f@outlook.com) on 2020/11/9
 */

'use strict';
import React from 'react';
import IconTag from './IconTag/IconTag';
import styles from '../Index.less';
/**
 * webpack打包，引用有问题
 */
// import {IconMap} from './utils';
import {Empty, Icon, Tree} from 'antd';
import ViewTitle from '../ViewTitle';
import ComponentBase from '../Base/ComponentBase';

const _theme = require('../../theme');

const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1400380_hjvm2icxm5o.js',
});
const IconMap = {
  0: <IconFont type='icongongchang'/>,
  1: <IconFont type='iconbumen'/>,
  2: <IconFont type='iconzibumen'/>,
  3: <IconFont type='iconzhicheng'/>,
  4: <IconFont type='icongongxu'/>,
  5: <IconFont type='iconshebei'/>,
  6: <IconFont type='iconshebei1'/>,
  7: <IconFont type='iconbeijian'/>,
  8: <IconFont type='iconrenwu'/>,
  9: <IconFont type='iconfeiyong'/>,
  10: <IconFont type='iconjihua'/>,
  11: <IconFont type='iconguanlian'/>,
};
const {TreeNode} = Tree;

class SiderTreePlus extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {checkedKeys: []};
  }

  componentDidMount() {
    this.onLoadData().then(res => {
      this.setState(res);
    });
  }

  async onLoadData() {
    const {table, findTable, dispatch, tenant} = this.props;
    const _table = findTable ? findTable : table;

    const {tenantName, tenantCode} = tenant;
    const payload = {table: _table};
    if (tenant) {
      payload['tenantCode'] = tenantCode;
      payload['isSuRegister'] = true;
    }

    const res = await dispatch({
      type: 'treeNode/findTreesWithAuth', payload,
    });
    if (!res) {
      this.requestReturn(null);
      return;
    }
    const res1 = await this.props.dispatch({
      type: 'treeNode/getNodes',
      payload: {table: _table, tenantCode, isSuRegister: true},
    });

    if (!res1) {
      this.requestReturn(null);
      return;
    }

    return {tree: res.result, nodes: res1.result};
  }

  onExpand = (_expandedKeys) => {
    const {dispatch, table} = this.props;
    let expandedKeys = typeof _expandedKeys === 'string' ? [_expandedKeys] : _expandedKeys;
    dispatch({
      type: 'treeNode/onDataLoad',
      payload: {
        table,
        expandedKeys,
      },
    });
  };

  onSelect = (selectedKeys) => {
    const treeId = selectedKeys.length > 0 ? selectedKeys[0] : undefined;
    if (!treeId) return;
    this.state.treeId = treeId;
    const {nodes} = this.state;
    const node = _.find(nodes, item => item.treeId === treeId);
    this.state.treeNode = node;
    const {onSelected} = this.props;
    onSelected && onSelected(node);
  };

  renderTreeTitle = (item) => {
    const {disableEditTable} = this.props;
    let {title, level, name, table, treeId, editable} = item;

    disableEditTable && disableEditTable.map(item => {
      if (table === item) {
        editable = false;
      }
    });

    const label = title ? title.label : '';
    const color = title ? title.color : _theme['primary-color'];

    let style = this.state.treeId && this.state.treeId === treeId ? styles.selected : styles.notSelected;

    return (
      <div className={style}>
        <IconTag className={styles.treeTitle} color={color} title={label} icon={IconMap[level]}/>
        <span>{name}</span>
      </div>
    );
  };

  renderTreeNodes = treeNodes => {
    return treeNodes && treeNodes.length ? treeNodes.map(item => {
      if (item) {
        const {treeId, children} = item;
        let clearDisabled = false;
        let deleteDisabled = false;

        if (children && children.length) {
          deleteDisabled = true;
          for (let baby of children) {
            if (baby) {
              const {children} = baby;
              if (children && children.length) {
                clearDisabled = true;
              }
            }
          }
        } else {
          clearDisabled = true;
        }
        return (
          <TreeNode
            title={this.renderTreeTitle(item, deleteDisabled, clearDisabled)}
            key={treeId}
          >
            {item.children && this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    }) : null;
  };

  refresh = () => {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode} = loginInfo;
    const {dispatch, table, onLoadData} = this.props;
    const treeId = this.state.treeId;
    const payload = {treeId, table, tenantCode};
    dispatch({
      type: 'treeNode/getInfoById',
      payload,
    });
    onLoadData && onLoadData(treeId);
  };

  onCheck = node => {
    const {onCheck} = this.props;
    const {checked} = node;
    const key = checked[checked.length - 1];
    const {nodes} = this.state;
    const _node = nodes.filter(item => item.treeId === key);
    onCheck && onCheck(key, _node[0]);
    this.setState({checkedKeys: [key]});
  };

  renderTree = () => {
    const {tree, treeId} = this.state;

    const {checkable} = this.props;
    let view = tree && tree.length ?
      <div>
        {tree && tree.length && <Tree
          showIcon
          onExpand={this.onExpand}
          onSelect={this.onSelect}
          defaultExpandAll={true}
          selectedKeys={[treeId]}
          autoExpandParent={false}
          checkedKeys={this.state.checkedKeys}
          checkStrictly={true}
          checkable={checkable}
          onCheck={this.onCheck}
        >
          {this.renderTreeNodes(tree)}
        </Tree>}
      </div> : <Empty style={{marginTop: 32}}/>;
    return view;

  };

  render() {
    const {title, selectedTreeId} = this.props;
    //selectedTreeId ? this.state.treeId = selectedTreeId : undefined;
    if (selectedTreeId) {
      this.state.treeId = selectedTreeId;
      this.onSelect([selectedTreeId]);
    }

    return (<div>
        {title && <ViewTitle
          style={{background: '#fff'}}
          title={title}

        >
        </ViewTitle>}
        {this.renderTree()}
      </div>
    );
  }
}

export default SiderTreePlus;
